﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YahooManaged.Finance;
using YahooManaged.Finance.API;
using YahooManaged.Base;
using System.IO;
using System.Collections.ObjectModel;

namespace download
{
    // 下载数据，存文件，读文件 工具类
    class Download
    {
        //下载from -> to这段时间 ids这些股票的日线数据，结果存在res中
        public static void DownloadData(string[] ids, DateTime fromDate, DateTime toDate, ref HistQuotesDataChain[] res)
        {
            HistQuotesInterval interval = HistQuotesInterval.Daily;
            //Download
            HistQuotesDownload dl = new HistQuotesDownload();
            HistQuotesResponse resp = dl.Download(ids, fromDate, toDate, interval);

            //Response/Result
            if (resp.Connection.State == ConnectionState.Success)
            {
                res = resp.Result;
            }
            else
                Console.WriteLine("Error cann't get yahoo finance data!");
        }

        //存个股数据到文件中
        public static void SaveData(HistQuotesDataChain qd, string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("date open low high close closeAdjust");
            int quotesCount = qd.Count;
            for (int i = qd.Count - 1; i >= 0; i--)
            {
                HistQuoteData cur = qd[i];
                sw.WriteLine(cur.TradingDate.ToString("yyyyMMdd") + " " + cur.Open + " " + cur.Low + " " + cur.High + " " + cur.Close + " " + cur.CloseAdjusted);
            }
            sw.Flush();
            sw.Close();
            fs.Close();
        }

        //从文件中读入数据，填入qd中，一个文件一个股票
        public static void LoadData(ref HistQuotesDataChain qd, string filename)
        {
            StreamReader din = File.OpenText(filename);
            string str = din.ReadLine(); // 跳过第一行
            qd = new HistQuotesDataChain();
            while ((str = din.ReadLine()) != null)
            {
                HistQuoteData hqd = new HistQuoteData();
                string[] tmp = str.Split(' ');
                hqd.TradingDate = DateTime.ParseExact(tmp[0], "yyyyMMdd", null);
                hqd.Open = Double.Parse(tmp[1]);
                hqd.Low = Double.Parse(tmp[2]);
                hqd.High = Double.Parse(tmp[3]);
                hqd.Close = Double.Parse(tmp[4]);
                hqd.CloseAdjusted = Double.Parse(tmp[5]);
                qd.Add(hqd);
            }
            din.Close();
        }
        
    }
}
